package com.lxj.controller;

import com.lxj.common.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author lxj
 * @date 2021/6/22 15:00
 * @Description:文件上传
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload.do")
    public Result upload(MultipartFile file, HttpServletRequest req) throws Exception{
        System.out.println(file);
        //该图片最终放在什么地方
        String realPath = req.getRealPath("imgs");
        String originalFilename  = file.getOriginalFilename();
        String suffix = originalFilename .substring(originalFilename .lastIndexOf(".") + 1);
        String fileName = UUID.randomUUID().toString() + "." + suffix;
        String diskFileName = realPath + "\\" + fileName;
        //将我们上传的文件写入到该文件夹里面
        File diskFile  = new File(diskFileName);
        FileOutputStream outputStream = new FileOutputStream(diskFile);
        InputStream inputStream = file.getInputStream();
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = inputStream.read(b)) != -1){
            outputStream.write(b,0,len);
        }
        outputStream.close();
        inputStream.close();
        String accessUrl = req.getContextPath() + "/imgs/" + fileName;
        return new Result(accessUrl);
    }
}
